﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DoAn_BumTruong_DesignPattern.Admin
{
    public partial class Menu : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }
        /// <summary>
        /// Khoi tao Facade
        /// </summary>
        Facades menufacades = new Facades();

        MenuController menuController = new MenuController();

        /// <summary>
        /// Thực hiện load toàn bộ dữ liệu
        /// </summary>
        /// 
        private void LoadData()
        {
            int howManyPage = 0;
            string moduleID = Request.QueryString["MenuID"] ?? "";
            string page = Request.QueryString["Page"] ?? "1";
            string fistPageUrl = Link.ToMenuAdmin("1");
            string pageUrl = Link.ToMenuAdmin("{0}");
            RepeaterMenu.DataSource = menufacades.PagingMenu(page, out howManyPage).OrderByDescending(mn => mn.MenuID);
            RepeaterMenu.DataBind();
            //Load du lieu len dropdownlist
            foreach (RepeaterItem item in RepeaterMenu.Items)
            {
                Label lbMenuID = (Label)item.FindControl("lbMenuType");
                DropDownList ddlTypes = (DropDownList)item.FindControl("ddlTypes");
                if (lbMenuID.Text != "")
                {
                    Menus data = menufacades.SignleMenu(lbMenuID.Text);
                    ddlTypes.SelectedValue = data.MenuType.ToString();
                }
            }
            PagesButton.ShowPage(int.Parse(page), howManyPage, fistPageUrl, pageUrl, true);
        }
        private Menus GetData()
        {
            Menus mn = new Menus();
            return mn;
        }
        protected override void OnInitComplete(EventArgs e)
        {
            base.OnInitComplete(e);
            RepeaterMenu.ItemCommand += RepeaterMenu_ItemCommand;

            //Lấy dữ liệu lên ddlType
            RepeaterMenu.ItemDataBound += RepeaterMenu_ItemDataBound;

            btnUpdateOrderNo.Click += btnUpdateOrderNo_Click;

            btDelete.Click += btDelete_Click;
        }

        void btDelete_Click(object sender, EventArgs e)
        {
            bool status = false;
            string Id = Request.Form["Id"] ?? "";
            if (Id != "")
            {
                foreach (string id in Id.Split(','))
                {
                    Menus m = menuController.Single(id);
                    if (m != null)
                        status = menufacades.DeleteMenu(m);
                    LoadData();
                    lblStatus.Text = status ? "Delete successful" : "Delete failed";
                }
            }   
        }

        void btnUpdateOrderNo_Click(object sender, EventArgs e)
        {
            string[] arr = Request.Form.AllKeys.Where(mn => mn.StartsWith("ord_")).ToArray();
            foreach (var item in arr)
            {
                int orderNo = int.Parse(Request.Form[item]);
                int id = int.Parse(item.Split('_')[1]);
                menuController.UpdateOrderNo(id, orderNo);
            }
            LoadData();
        }

        void RepeaterMenu_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Menus mn = new Menus();
                mn = (Menus)e.Item.DataItem;
                DropDownList ddlTypes = (DropDownList)e.Item.FindControl("ddlTypes");
                int i = 0;
                foreach (string item in Enum.GetNames(typeof(MenuTypes)))
                {
                    ddlTypes.Items.Add(new ListItem(item, i + ""));
                    i += 1;
                }
                ddlTypes.SelectedIndex = mn.MenuType;
            }
        }

        void RepeaterMenu_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "UpdateActive")
            {
                string[] arg = e.CommandArgument.ToString().Split('_');
                if (menufacades.UpdateActiveMenu(int.Parse(arg[0]), !Convert.ToBoolean(arg[1])))
                    LoadData();
            }
        }

        protected void ddlTypes_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool state = false;
            DropDownList ddlType = sender as DropDownList;
            int index = ((RepeaterItem)ddlType.NamingContainer).ItemIndex;
            string[] id = Request.Form.GetValues("menu_id");
            string[] arr = id[index].Split('_');
            int s = Convert.ToInt32(ddlType.SelectedValue);
            switch (s)
            {
                case (int)MenuTypes.Parent:
                    state = menufacades.UpdateMenuTypeMenu(Convert.ToInt32(arr[0]), ((int)MenuTypes.Parent));
                    break;
                case (int)MenuTypes.Child:
                    state = menufacades.UpdateMenuTypeMenu(Convert.ToInt32(arr[0]), ((int)MenuTypes.Child));
                    break;
                default:
                    break;
            }
            LoadData();
            lblStatus.Text = state ? "Update successful" : "Update failed";
        }
    }
}